<template>
    <div>
        <van-nav-bar title="编辑个人信息" style="background-color: #FFD85F;" class="headera">
            <template #left>
                <van-icon name="arrow-left" @click="goBack" />
            </template>
        </van-nav-bar>

        <div style="background-color: #FFF7E1; min-height: 100vh; padding: 20px;">
            <van-form @submit="onSubmit">
                <!-- 编辑信息卡片 -->
                <div class="edit-card">
                    <!-- 用户信息部分 -->

                    <div class="field-card">
                        <van-field v-model="user.username" label="用户名" placeholder="请输入用户名" />
                    </div>
                    <div class="field-card">
                        <van-field v-model="user.email" type="email" label="邮箱" placeholder="请输入邮箱" />
                    </div>
                    <div class="field-card">
                        <van-field v-model="user.age" type="number" label="年龄" placeholder="请输入年龄" />
                    </div>

                    <!-- 性别选择部分 -->
                    <van-radio-group v-model="user.gender">
                        <van-cell-group>
                            <van-cell title="性别">
                                <template #right-icon>
                                    <van-radio :name="'男'" :value="'男'">男</van-radio>
                                    <van-radio :name="'女'" :value="'女'">女</van-radio>
                                </template>
                            </van-cell>
                        </van-cell-group>
                    </van-radio-group>

                    <!-- 健康状况选择 -->
                    <div @click="showHealthPicker = true">
                        <van-field v-model="user.healthStatus" label="健康状况" readonly placeholder="请选择健康状况" />
                    </div>

                    <!-- 文件上传部分 -->
                    <div class="upload-field">
                        <van-uploader v-model="fileList" :max-count="1" :after-read="handleAfterRead"
                            :preview-image="true" :preview-full-image="true" accept="image/*" />
                    </div>
                </div>

                <!-- 保存按钮 -->
                <div class="save-button-wrapper">
                    <van-button class="save-button" type="primary" block native-type="submit">保存</van-button>
                </div>
            </van-form>
        </div>
        <van-popup v-model="showHealthPicker" position="bottom">
            <van-picker show-toolbar :columns="healthOptions" @confirm="onHealthConfirm"
                @cancel="showHealthPicker = false" />
        </van-popup>
    </div>

</template>

<script>
import axios from 'axios';

export default {
    components: {},
    data() {
        return {
            showHealthPicker: false,
            healthOptions: ['无', '高血压', '高胆固醇', '糖尿病'],
            user: {  // 用户信息对象
                username: '',
                email: '',
                age: '',
                gender: '',
                healthStatus: '无',
                avatar: '',  // 默认头像字段
            },
            fileList: [], // 存储上传的文件列表
        };
    },
    methods: {
        onHealthConfirm(value) {
            this.user.healthStatus = value;
            this.showHealthPicker = false;
        },
        goBack() {
            this.$router.back();
        },
        async onSubmit() {
            let avatarUrl = this.user.avatar; // 默认使用当前头像


            // 如果用户上传了新头像
            if (this.fileList.length > 0) {
                // 上传头像文件
                const formData = new FormData();
                formData.append('file', this.fileList[0].file);

                try {
                    const response = await axios.post('http://localhost:8081/wx/storage/create', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    });

                    if (response.data.errno === 0) {
                        avatarUrl = response.data.data.url; // 获取上传后的头像URL
                    } else {
                        axios.post('http://localhost:8081/wx/storage/create', this.fileList.url, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        })
                    }
                } catch (error) {
                    console.error('头像上传失败:', error);
                    this.$toast.fail('头像上传失败');
                    return;
                }
            }

            // 提交的数据，包括所有用户信息，和上传后的头像 URL（如果有）
            const userData = {
                ...this.user,
                avatar: avatarUrl,  // 头像URL
            };

            const token = localStorage.getItem('token'); // 从 localStorage 获取 token
            console.log('提交的用户数据:', userData);
            // 提交用户数据到服务器
            try {
                const res = await axios.post('http://localhost:8081/wx/admin/update', userData, {
                    headers: {
                        token: token, // 添加 Bearer Token 认证
                        'Content-Type': 'application/json' // 确保 Content-Type 正确
                    }
                });
                if (res.data.errno === 0) {
                    this.$toast.success('保存成功');
                    this.goBack(); // 成功后返回
                } else {
                    this.$toast.fail(res.data.errmsg);
                }
            } catch (error) {
                console.error('保存失败:', error);
                this.$toast.fail('保存失败');
            }
        },
        handleAfterRead(file) {
            // 处理上传的文件
            console.log(file);
            this.fileList = [file]; // 确保只有一个文件
        },
    },
    created() {
        // 请求后端接口，获取用户信息
        axios.get("http://localhost:8081/wx/admin/user?id=" + this.$route.params.id)
            .then(res => {
                if (res.data.errno === 0) {
                    this.user = res.data.data; // 设置用户信息
                    if (this.user.avatar) {
                        this.fileList = [{ url: this.user.avatar }]; // 设置头像
                    }
                } else {
                    this.$toast.fail(res.data.errmsg);
                }
            })
            .catch(error => {
                console.error("请求失败:", error);
            });
    }
};
</script>

<style scoped>
.edit-card {
    padding: 20px;
    background-color: #FFD85F;
    border-radius: 10px;
    box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
}

.field-card {
    background-color: #ffffff;
    border-radius: 12px;
    padding: 12px 16px;
    margin-bottom: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: box-shadow 0.3s ease;
}

.save-button-wrapper {
    margin-top: 20px;
    padding: 0 10px;
}

.save-button {
    background-color: #FFD85F;
    color: #000;
    font-weight: bold;
    border-radius: 20px;
}

/* 文件上传样式 */
.upload-field {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    padding: 10px;
}

.van-uploader {
    width: 100%;
}

.van-uploader__preview {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 8px;
    margin-right: 10px;
}

.van-uploader__delete {
    right: -6px;
    top: -6px;
    background-color: rgba(255, 255, 255, 0.8);
}
</style>
